<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\UserAddressRequest;
use App\Http\Resources\UserAddressResource;
use App\Models\District;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserAddressController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $results = UserAddress::with(['province', 'city', 'district'])
            ->where('uid', \Auth::id())
            ->orderBy('priority', 'desc')
            ->get();

        $resource = UserAddressResource::collection($results);

        return api(RET_OK, RET_SUCCESS_MSG, $resource);

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserAddressRequest $request)
    {
        $data = $request->all();
        $data['uid'] = \Auth::id();
        $result = UserAddress::create($data);

        return api(RET_OK, RET_SUCCESS_MSG, $result);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $result = UserAddress::with(['province', 'city', 'district'])->findOrFail($id);
        $resource = new UserAddressResource($result);

        return api(RET_OK, RET_SUCCESS_MSG, $resource);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserAddressRequest $request, $id)
    {
        $result = UserAddress::findOrFail($id);
        $result->update($request->except(['uid']));

        return api(RET_OK, RET_SUCCESS_MSG, $result);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $result = UserAddress::findOrFail($id);
        $result->delete();

        return api(RET_OK, RET_SUCCESS_MSG, []);
    }
}
